﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Ovvio.Web.Areas.Admin.Models;
using Ovvio.Business;
using Ovvio.Web.Core;
using Ovvio.Data;
using Ovvio.Web.Areas.Admin.ModelProviders;

namespace Ovvio.Web.Areas.Admin.Controllers
{
    public class ProductsController : BaseController<int, ProductModel, Product, OvvioDataContext>
    {
        public ProductsController() : base(new ProductModelProvider()) { }

        public override ActionResult Index()
        {
            var service = new ServiceBase<int, ProductCategory, OvvioDataContext>(p => p.Id);

            var list = service.GetEntities().Select(i => i.Category).ToList();
            list.Insert(0, "Select Category");
            ViewData["Categories"] = list;
            return base.Index();
        }
        
        public ActionResult List(string productName, string category)
        {
            var service = new ServiceBase<int, ProductCategory, OvvioDataContext>(p => p.Id);

            var list = service.GetEntities().Select(i => i.Category).ToList();
            
            list.Insert(0, "Select Category");

            var selectList = new SelectList(list, string.IsNullOrEmpty(category) ? list.First() : category);
            ViewData["Categories"] = selectList;
            ViewData["ProductName"] = productName;
            Func<Product, bool> predicate = null;

            if (!string.IsNullOrEmpty(productName) && !string.IsNullOrEmpty(category))
                predicate = p => p.Name.ToUpper().Contains(productName.ToUpper()) && p.ProductCategory != null &&
                p.ProductCategory.Category.ToUpper() == category.ToUpper();
            else if (!string.IsNullOrEmpty(category))
                predicate = p => p.ProductCategory != null && 
                p.ProductCategory.Category.ToUpper() == category.ToUpper();
            else if (!string.IsNullOrEmpty(productName))
                predicate = p => p.Name.ToUpper().Contains(productName.ToUpper());

            if (predicate != null)
                return View(base._modelProvider.GetList(predicate));

            return base.Index();
        }

        public ActionResult Image(int id)
        {
            var image = ((ProductModelProvider)_modelProvider).GetImage(id);

            if (image != null)
                return File(image, "image/jpg");

            return File(new byte[] { }, "image/jpg");
        }

        public ActionResult Thumb(int id)
        {
            var image = ((ProductModelProvider)_modelProvider).GetThumbnail(id);

            if (image != null)
                return File(image, "image/jpg");

            return File(new byte[] { }, "image/jpg");
        }
    }
}
